"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";

import { useAutoScrollToBottom } from "~/components/hooks/useAutoScrollToBottom";
import { TooltipProvider } from "~/components/ui/tooltip";
import { 
  sendMessage, 
  useInitTeamMembers, 
  useInitSession, 
  useStore,
 
} from "~/core/store";
import { cn } from "~/core/utils";

import { AppHeader } from "./_components/AppHeader";
import { InputBox } from "./_components/InputBox";
import { MessageHistoryView } from "./_components/MessageHistoryView";
import { LoginDialog } from "./_components/LoginDialog";
import { RegisterDialog } from "./_components/RegisterDialog";
import { Sidebar } from "./_components/Sidebar";
import { ScrollArea } from "~/components/ui/scroll-area";
import { SearchDialog } from "./_components/SearchDialog";

export default function HomePage() {
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);
  const [isSearchDialogOpen, setIsSearchDialogOpen] = useState(false);

  // 获取状态和方法
  const { 
    newConversation,
    auth,
    messages,
    responding,
    sessionList,
    fetchSessionList
  } = useStore();
  
  const handleSendMessage = useCallback(
    async (
      content: string,
      config: { deepThinkingMode: boolean; searchBeforePlanning: boolean },
    ) => {
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      await sendMessage(
        {
          id: Date.now().toString(),
          role: "user",
          type: "text",
          content,
        },
        config,
        { abortSignal: abortController.signal },
      );
      abortControllerRef.current = null;
      
      // 发送消息后刷新会话列表
      fetchSessionList();
    },
    [],
  );

  // 使用客户端渲染保护
  const [isMounted, setIsMounted] = useState(false);
  
  // 仅在客户端挂载后初始化
  useEffect(() => {
    setIsMounted(true);
  }, []);
  
  // 初始化团队成员和会话
  useInitTeamMembers();
  useInitSession();
  useAutoScrollToBottom(scrollAreaRef, responding);
  
  // 初始化登录状态
  useEffect(() => {
    const token = localStorage.getItem('access_token');
    const username = localStorage.getItem('username');
  
    if (token && username) {
      useStore.setState({
        auth: { isLoggedIn: true, username }
      });
      // 调试日志
    console.log('User logged in, fetching sessions');
    
    // 登录后立即获取会话列表
    useStore.getState().fetchSessionList();
  }
  }, []);
  // 监听登录状态变化
useEffect(() => {
  if (auth.isLoggedIn) {
    // 调试日志
    console.log('Login status changed, fetching sessions');
    
    // 登录状态变化时获取会话列表
    useStore.getState().fetchSessionList();
  }
}, [auth.isLoggedIn]);

  // 是否处于对话模式
  const isConversationMode = messages.length > 0;
  
  // 弹窗状态
  const [loginOpen, setLoginOpen] = useState(false);
  const [registerOpen, setRegisterOpen] = useState(false);
  
  // 侧边栏是否弹出
  const [isSidebarExpanded, setIsSidebarExpanded] = useState(true);
  
  // 新建对话处理函数
  const handleNewConversation = () => {
    newConversation();
    console.log("开始新的对话");
  };

  // 服务器端或客户端初始渲染时的占位内容
  if (!isMounted) {
    return (
      <div className="h-screen w-full bg-gradient-to-b from-background to-secondary/20 flex items-center justify-center">
        <div className="animate-pulse text-primary">
          <div className="mb-3 p-2 rounded-full bg-primary/10 border border-primary/30">
            <div className="h-16 w-16 rounded-full bg-primary/20"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <TooltipProvider delayDuration={150}>
      {/* 登录和注册对话框 */}
      <LoginDialog
        open={loginOpen}
        onOpenChange={setLoginOpen}
        onLoginSuccess={(username) => {
          setLoginOpen(false);
          // 登录成功后获取会话列表
          useStore.getState().fetchSessionList();
        }}
        onNavigateToRegister={() => {
          setLoginOpen(false);
          setRegisterOpen(true);
        }}
      />
      
      <RegisterDialog
        open={registerOpen}
        onOpenChange={setRegisterOpen}
        onRegisterSuccess={() => {
          setRegisterOpen(false);
          setLoginOpen(true);
        }}
        onNavigateToLogin={() => {
          setRegisterOpen(false);
          setLoginOpen(true);
        }}
      />

      <SearchDialog 
        open={isSearchDialogOpen}
        onClose={() => setIsSearchDialogOpen(false)}
      />

      {/* 整个布局容器 */}
      <div className="flex flex-col h-screen w-full">
        {/* 应用头部 */}
        <header className={cn(
          "sticky top-0 z-50 flex w-full items-center backdrop-blur-md bg-white/95 border-b border-secondary/20",
          "transition-all duration-700 ease-in-out h-20"
        )}>
          <div className="w-full px-4">
            <AppHeader onLoginClick={() => setLoginOpen(true)} />
          </div>
        </header>
        
        <div className="flex flex-1 min-h-0">
          {/* 侧边栏 */}
          <div className={cn(
            "fixed top-20 z-40 border-r border-secondary/20 shadow-sm bg-gradient-to-b from-background to-secondary/20",
            "transition-all duration-300 ease-in-out overflow-hidden",
            "h-[calc(100vh-5rem)]",
            isSidebarExpanded ? "w-64" : "w-16"
          )}>
            <Sidebar 
              isExpanded={isSidebarExpanded}
              onToggle={() => setIsSidebarExpanded(!isSidebarExpanded)}
              onNewChat={handleNewConversation}
              onOpenSearch={() => setIsSearchDialogOpen(true)}
            />
          </div>
          
          {/* 内容区域 */}
          <div 
            className={cn(
              "flex-1 flex flex-col min-h-0",
              "transition-all duration-300 ease-in-out",
              isSidebarExpanded ? "ml-64" : "ml-16"
            )}
          >
            {/* 聊天内容区域 */}
            <div className="flex-1 min-h-0">
              <ScrollArea 
                className="h-full w-full bg-gradient-to-b from-background to-secondary/20"
                ref={scrollAreaRef}
              >
                <div className="flex flex-col items-center">
                  <main className="w-full px-4 pb-48 relative">
                    {/* 对话内容视图 */}
                    <div 
                      className={cn(
                        "w-page mx-auto transition-all duration-700 ease-in-out max-w-5xl",
                        isConversationMode ? "opacity-100 translate-y-0" : "opacity-0 translate-y-12"
                      )}
                    >
                      <MessageHistoryView
                        className="w-page mx-auto"
                        messages={messages}
                        loading={responding}
                      />
                    </div>
                    {/* 首页欢迎内容 - 带有平滑过渡效果 */}
                    <div 
                      className={cn(
                        "absolute inset-x-0 mx-auto top-[5vh]",
                        "transition-all duration-700 ease-in-out",
                        isConversationMode 
                          ? "opacity-0 pointer-events-none translate-y-[-20vh]" 
                          : "opacity-100 translate-y-0"
                      )}
                      style={{ maxWidth: "640px" }}
                    >
                      <div className="flex w-full flex-col items-center">
                        <div className={cn(
                          "mb-3 p-2 rounded-full bg-primary/10 border border-primary/30",
                          "transition-all duration-700 ease-in-out",
                          isConversationMode ? "scale-0" : "scale-100"
                        )}>
                          <div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center">
                            <div className="h-10 w-10 relative flex items-center justify-center">
                              <img 
                                src="/脑电.png" 
                                alt="脑电图"
                                width={32}
                                height={32}
                                className="object-contain"
                              />
                            </div>
                          </div>
                        </div>
                        <h3 className={cn(
                          "mb-3 text-center text-3xl font-medium text-primary",
                          "transition-all duration-700 ease-in-out",
                          isConversationMode ? "opacity-0 scale-95" : "opacity-100 scale-100"
                        )}>
                          赛博华佗，医严定镇
                        </h3>
                        <div className={cn(
                          "px-4 py-2 rounded-xl bg-white/80 shadow-sm border border-secondary/30 text-center text-lg text-muted-foreground",
                          "transition-all duration-700 ease-in-out",
                          isConversationMode ? "opacity-0 scale-95" : "opacity-100 scale-100"
                        )}>
                          <a
                            href="https://github.com/SDU-Gary/DeepMedical"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-primary font-medium hover:underline"
                          >
                            医智寻源
                          </a>
                          ，一个基于人工智能的医学知识图谱搜索引擎，致力于为用户提供精准、快速的医学信息检索服务。
                        </div>
                      </div>
                    </div>
                  </main>
                </div>
              </ScrollArea>
            </div>
            
            {/* 输入框区域 */}
            <footer
              className={cn(
                "sticky bottom-0 z-30 w-full",
                "flex justify-center px-4 py-4 bg-gradient-to-t from-background via-background/90 to-transparent",
                "transition-all duration-300 ease-in-out"
              )}
            >
              <div 
                className={cn(
                  "flex flex-col items-center w-full transition-all duration-700 ease-in-out mx-auto",
                  "max-w-3xl"
                )}
              >
                <div className="flex flex-col overflow-hidden rounded-[24px] border border-secondary/50 bg-white shadow-lg w-full">
                  <InputBox
                    size={isConversationMode ? "normal" : "large"}
                    responding={responding}
                    onSend={handleSendMessage}
                    onCancel={() => {
                      abortControllerRef.current?.abort();
                      abortControllerRef.current = null;
                    }}
                  />
                </div>
                <div className={cn(
                  "mt-2 text-xs text-muted-foreground/70 transition-opacity duration-700 ease-in-out",
                  isConversationMode ? "opacity-100" : "opacity-0"
                )}>
                  医智寻源 - 提供精准医学知识检索服务
                </div>
              </div>
            </footer>
          </div>
        </div>
      </div>
    </TooltipProvider>
  );
}